import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {MyTableConfig} from '../../../share/components/ant-table/ant-table.component';
import {PageHeaderType} from '../../../share/components/page-header/page-header.component';
import {NzTableQueryParams} from 'ng-zorro-antd/table';
import {SearchCommonVO} from '../../../core/services/types';
import {finalize} from 'rxjs/operators';
import {MyGradesModel, MyGradesService, TestUserDetail} from '../../../core/services/http/exams-manage/my-grades.service';
import {Router} from '@angular/router';
import {WindowService} from '../../../core/services/common/window.service';
import {ActionCode} from 'src/app/configs/actionCode';


interface SearchParam {
  name: string;
}

@Component({
  selector: 'app-my-grades',
  templateUrl: './my-grades.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyGradesComponent implements OnInit {
  ActionCode = ActionCode;
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  searchParam: Partial<SearchParam> = {};
  tableConfig!: MyTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '我的成绩',
    breadcrumb: ['在线考试', '我的成绩']
  };
  dataList: MyGradesModel[] = [];
  userIdSession!: number;
  isVisible = false;
  isConfirmLoading = false;
  dataTest: TestUserDetail[] = [];

  constructor(private dataService: MyGradesService, private cdr: ChangeDetectorRef,
              private router: Router, private windowServe: WindowService) {
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
      filters: this.searchParam,
      userId: this.userIdSession
    };
    this.dataService.getResults(params).pipe(finalize(() => {
      this.tableLoading(false);
    })).subscribe((data => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
    }));
  }

  /*重置*/
  resetForm(): void {
    this.searchParam = {};
    this.getDataList();
  }

  handleOk(): void {
    this.isConfirmLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isConfirmLoading = false;
    }, 1000);
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  detail(id: number, dex: number): void {
    this.isVisible = true;
    this.dataTest.length = 0;
    this.dataService.getUserTestDetail({userId: id, questionTestId: dex}).subscribe(test => {
      test.forEach(item => {
        this.dataTest.push(item);
      });
    });
  }

  results(user: number, questionTest: number): void {
    this.router.navigate(['/default/online-test/my-grades/exam-wrong-topic', user, questionTest]);
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  ngOnInit(): void {
    this.initTable();
    this.userIdSession = JSON.parse(this.windowServe.getStorage('user')!);
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: false,
      headers: [
        {
          title: '考试名称',
          field: 'questionTestName',
          width: 100,
        },
        {
          title: '考试次数',
          width: 100,
          field: 'countTest',
        },
        {
          title: '最高分',
          width: 100,
          field: 'maxScore',
        },
        {
          title: '是否通过',
          width: 100,
          field: 'passFlag',
          pipe: 'passFlag'
        },
        {
          title: '最后考试时间',
          width: 100,
          field: 'lastTestTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 60,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }

}
